/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.dream.service.impl;

import com.dream.repository.TaskWorkRepository;
import com.dream.service.TaskWorkService;
import com.dream.service.dto.TaskGatherDto;
import com.dream.service.dto.TaskWorkDto;
import com.dream.service.dto.TaskWorkQueryCriteria;
import com.dream.service.mapstruct.TaskWorkMapper;
import com.dream.util.EntityConvertUtils;
import com.dream.utils.*;
import com.dream.domain.TaskWork;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.*;
import java.io.IOException;
import javax.servlet.SessionCookieConfig;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author syl
* @date 2020-07-06
**/
@Service
@RequiredArgsConstructor
public class TaskWorkServiceImpl implements TaskWorkService {
    private static Logger log = LoggerFactory.getLogger(TaskWorkServiceImpl.class);
    private final TaskWorkRepository taskWorkRepository;
    private final TaskWorkMapper taskWorkMapper;

    @Override
    public Map<String,Object> queryAll(TaskWorkQueryCriteria criteria, Pageable pageable){
        Page<TaskWork> page = taskWorkRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(taskWorkMapper::toDto));
    }

    @Override
    public Page<TaskWork>  queryPage(TaskWorkQueryCriteria criteria, Pageable pageable){
        return taskWorkRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
    }

    @Override
    public List<TaskWorkDto> queryAll(TaskWorkQueryCriteria criteria){
        return taskWorkMapper.toDto(taskWorkRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public TaskWorkDto findById(Integer id) {
        TaskWork taskWork = taskWorkRepository.findById(id).orElseGet(TaskWork::new);
        ValidationUtil.isNull(taskWork.getId(),"TaskWork","id",id);
        return taskWorkMapper.toDto(taskWork);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TaskWorkDto create(TaskWork resources) {

        return taskWorkMapper.toDto(taskWorkRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TaskWork resources) {
        TaskWork taskWork = taskWorkRepository.findById(resources.getId()).orElseGet(TaskWork::new);
        ValidationUtil.isNull( taskWork.getId(),"TaskWork","id",resources.getId());
        taskWork.copy(resources);
        taskWorkRepository.save(taskWork);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            taskWorkRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<TaskWorkDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (TaskWorkDto taskWork : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("项目名称", taskWork.getDeptName());
            map.put("任务名称", taskWork.getName());
            map.put("是否完结", "1".equals(taskWork.getTaskStatus())?"完结":"未完结");
            map.put("任务开始日期", taskWork.getStartDate());
            map.put("任务结束日期", taskWork.getEndDate());
            map.put("任务开始时间", DateUtil.localDateTimeFormatyMdHms(DateUtil.fromTimeStamp(taskWork.getStartTime().getTime())));
            map.put("任务结束时间", DateUtil.localDateTimeFormatyMdHms(DateUtil.fromTimeStamp(taskWork.getEndTime().getTime())));
            map.put("工作时长", taskWork.getWorkTime());
            map.put("工作内容", taskWork.getWorkContent());
            map.put("任务领取", taskWork.getTaskUserId());
            map.put("部门名称", taskWork.getDeptName());
            map.put("审核人", taskWork.getLeaderName());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public List<TaskGatherDto> gather(TaskWorkQueryCriteria criteria) {
        List<Object[]> objects = null;
        if(null == criteria.getDeptId() ){
            if(StringUtils.isEmpty(criteria.getBlurry())) {
                objects = taskWorkRepository.queryByDate(criteria.getStartDate(), criteria.getEndDate());
            }else{
                objects = taskWorkRepository.queryByDateAndBlurry(criteria.getStartDate(), criteria.getEndDate(),criteria.getBlurry());
            }
        }else{
            if(null != criteria.getTaskUserId()){
                if(StringUtils.isEmpty(criteria.getBlurry())) {
                    objects = taskWorkRepository.queryByUserId(criteria.getStartDate(), criteria.getEndDate(), criteria.getTaskUserId());
                }else{
                    objects = taskWorkRepository.queryByUserIdAndBlurry(criteria.getStartDate(), criteria.getEndDate(), criteria.getTaskUserId(), criteria.getBlurry());

                }
            }else if(null !=criteria.getLeaderId()){
                if(StringUtils.isNotEmpty(criteria.getBlurry())) {
                    objects = taskWorkRepository.queryByLeader(criteria.getStartDate(), criteria.getEndDate(), criteria.getLeaderId());
                }else{
                    objects = taskWorkRepository.queryByLeaderAndBlurry(criteria.getStartDate(), criteria.getEndDate(), criteria.getLeaderId(), criteria.getBlurry());

                }
            }else{
                if(StringUtils.isNotEmpty(criteria.getBlurry())) {
                    objects = taskWorkRepository.queryByDate(criteria.getStartDate(), criteria.getEndDate(), criteria.getDeptId());
                }else{
                    objects = taskWorkRepository.queryByDateAndBlurry(criteria.getStartDate(), criteria.getEndDate(), criteria.getDeptId(), criteria.getBlurry());

                }
            }
        }
        if(null !=objects){
            List<TaskGatherDto> taskGatherDtos = null;
            try {
                taskGatherDtos = EntityConvertUtils.objectToBean(objects, TaskGatherDto.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return taskGatherDtos;
        }
        return null;
    }

    @Override
    public void downloadGather(TaskWorkQueryCriteria criteria,HttpServletResponse response) throws IOException {
        List<TaskGatherDto> list = this.gather(criteria);
        List<Map<String, Object>> resut = new ArrayList<>();
        if(list == null){
            log.error("当前数据为空");
            return;
        }
        String startDate = criteria.getStartDate();
        String endDate = criteria.getEndDate();
        List<String> twoDaysDay = DateUtil.getTwoDaysDay(startDate, endDate);
        Map<String,TaskGatherDto> workHourMap  = new HashMap<>();
        Map<String,Object> dateMap = new HashMap<>();
        for (TaskGatherDto taskGatherDto : list) {
            String key = taskGatherDto.getItemName() + taskGatherDto.getTaskUserName();
            String key1 = taskGatherDto.getItemName() + taskGatherDto.getTaskUserName() +taskGatherDto.getStartDate();
            dateMap.put(key1,taskGatherDto.getWorkHour());
            if(workHourMap.containsKey(key)){
                TaskGatherDto taskGatherDto1 = workHourMap.get(key);
                taskGatherDto.setTotalHour(taskGatherDto1.getTotalHour()+taskGatherDto.getWorkHour());
            }else{
                taskGatherDto.setTotalHour(taskGatherDto.getWorkHour());
            }
            workHourMap.put(key,taskGatherDto);
        }
        Set<String> set = new HashSet<>();
        for (TaskGatherDto taskGatherDto : list) {
            Map<String,Object> map = new HashMap<>();
            String key = taskGatherDto.getItemName() + taskGatherDto.getTaskUserName();
            if(set.contains(key)){
                continue;
            }else{
                set.add(key);
            }
            TaskGatherDto taskGatherDto1 = workHourMap.get(key);
            map.put("项目名称",taskGatherDto.getItemName());
            map.put("任务领取人",taskGatherDto.getTaskUserName());
            map.put("总工时",taskGatherDto1.getTotalHour());
            for (String date : twoDaysDay) {
                String dateKey = key + date;
                if(date.equals(taskGatherDto.getStartDate())){
                    map.put(date,taskGatherDto.getWorkHour());
                }else if(dateMap.containsKey(dateKey)){
                    map.put(date,dateMap.get(dateKey));
                }else{
                    map.put(date,0);
                }
            }
            resut.add(map);
        }
        FileUtil.downloadExcel(resut, response);
    }
}